<template>
  <div class="auth-container" :class="{ show: isVisible }">
    <div class="auth-card">
      <div class="watermark">WWH-OJ</div>
      <div class="logo">
        <img src="../assets/logo.svg" alt="WWH-OJ Logo" class="logo-img" />
        <h1>WWH-OJ</h1>
      </div>
      <div class="form-container">
        <h2>{{ isLogin ? '登录' : '注册' }}</h2>
        <form @submit.prevent="handleSubmit">
          <!-- 用户名 -->
          <div class="input-group">
            <input 
              type="text" 
              v-model="formData.username" 
              required 
              placeholder="用户名" 
              maxlength="16"
              @input="validateUsername"
            />
            <span class="input-icon">👤</span>
            <span class="error-message" v-if="errors.username">{{ errors.username }}</span>
          </div>

          <!-- 密码 -->
          <div class="input-group">
            <input 
              type="password" 
              v-model="formData.password" 
              required 
              placeholder="密码" 
              :maxlength="isLogin ? 32 : 18"
              @input="validatePassword"
            />
            <span class="input-icon">🔒</span>
            <span class="error-message" v-if="errors.password">{{ errors.password }}</span>
          </div>

          <!-- 注册时额外的字段 -->
          <template v-if="!isLogin">
            <!-- 邮箱 -->
            <div class="input-group">
              <input 
                type="email" 
                v-model="formData.email" 
                required 
                placeholder="邮箱"
                @input="validateEmail"
              />
              <span class="input-icon">✉️</span>
              <span class="error-message" v-if="errors.email">{{ errors.email }}</span>
            </div>

            <!-- 昵称 (可选) -->
            <div class="input-group">
              <input 
                type="text" 
                v-model="formData.nick_name" 
                placeholder="昵称 (可选)" 
                maxlength="32"
              />
              <span class="input-icon">📝</span>
            </div>
          </template>

          <!-- 记住我 (仅登录时显示) -->
          <div v-if="isLogin" class="remember-me">
            <label>
              <input type="checkbox" v-model="rememberMe"> 记住我
            </label>
          </div>

          <button 
            type="submit" 
            class="submit-btn" 
            :disabled="isSubmitting"
          >
            {{ isSubmitting ? '处理中...' : (isLogin ? '登录' : '注册') }}
          </button>
        </form>

        <!-- 表单底部 -->
        <div class="form-footer">
          <button @click="toggleForm" class="toggle-btn">
            {{ isLogin ? '没有账号？注册' : '已有账号？登录' }}
          </button>
          
          <!-- 第三方登录 -->
          <div v-if="isLogin" class="social-login">
            <p class="social-text">其他登录方式</p>
            <div class="social-buttons">
              <button class="social-btn wechat" title="微信登录">
                <span class="social-icon">📱</span>
              </button>
              <button class="social-btn qq" title="QQ登录">
                <span class="social-icon">💬</span>
              </button>
              <button class="social-btn phone" title="手机登录">
                <span class="social-icon">📞</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import authApi from '../api/auth'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const isVisible = ref(true)
const isLogin = ref(true)
const isSubmitting = ref(false)
const rememberMe = ref(false)

const formData = ref({
  username: '',
  password: '',
  email: '',
  nick_name: ''
})

const errors = ref({
  username: '',
  password: '',
  email: ''
})

// 表单验证
const validateUsername = () => {
  const username = formData.value.username
  if (username.length < 3) {
    errors.value.username = '用户名至少需要3个字符'
  } else if (username.length > 16) {
    errors.value.username = '用户名最多16个字符'
  } else if (!/^[a-zA-Z0-9_-]+$/.test(username)) {
    errors.value.username = '用户名只能包含字母、数字、下划线和连字符'
  } else {
    errors.value.username = ''
  }
}

const validatePassword = () => {
  const password = formData.value.password
  if (isLogin.value) {
    if (password.length < 6) {
      errors.value.password = '密码至少需要6个字符'
    } else {
      errors.value.password = ''
    }
  } else {
    if (password.length < 8) {
      errors.value.password = '密码至少需要8个字符'
    } else if (password.length > 18) {
      errors.value.password = '密码最多18个字符'
    } else if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(password)) {
      errors.value.password = '密码必须包含大小写字母和数字'
    } else {
      errors.value.password = ''
    }
  }
}

const validateEmail = () => {
  const email = formData.value.email
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(email)) {
    errors.value.email = '请输入有效的邮箱地址'
  } else {
    errors.value.email = ''
  }
}

const handleSubmit = async () => {
  if (isSubmitting.value) return

  // 验证表单
  validateUsername()
  validatePassword()
  if (!isLogin.value) {
    validateEmail()
  }

  // 检查是否有错误
  if (Object.values(errors.value).some(error => error)) {
    return
  }

  isSubmitting.value = true

  try {
    if (isLogin.value) {
      // 登录请求
      const response = await authApi.login({
        username: formData.value.username,
        password: formData.value.password
      })

      if (response.code === 200) {
        ElMessage.success('登录成功')
        // 更新用户信息
        await userStore.fetchUserInfo()
        router.push('/')
        emit('close')
      }
    } else {
      // 注册请求
      const response = await authApi.register({
        username: formData.value.username,
        password: formData.value.password,
        email: formData.value.email,
        nick_name: formData.value.nick_name
      })

      if (response.code === 200) {
        ElMessage.success('注册成功')
        isLogin.value = true
        formData.value = {
          username: formData.value.username,
          password: '',
          email: '',
          nick_name: ''
        }
      }
    }
  } catch (error) {
    console.error('请求失败:', error)
  } finally {
    isSubmitting.value = false
  }
}

const toggleForm = () => {
  isLogin.value = !isLogin.value
  formData.value = {
    username: '',
    password: '',
    email: '',
    nick_name: ''
  }
  errors.value = {
    username: '',
    password: '',
    email: ''
  }
}

const emit = defineEmits(['close'])
</script>

<style scoped>
.auth-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  z-index: 1000;
}

.auth-card {
  position: relative;
  width: 400px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  padding: 40px;
  overflow: hidden;
}

.watermark {
  position: absolute;
  bottom: 20px;
  right: 20px;
  font-size: 100px;
  color: rgba(0, 0, 0, 0.03);
  pointer-events: none;
  font-weight: bold;
  transform: rotate(-45deg);
}

.logo {
  text-align: center;
  margin-bottom: 30px;
}

.logo-img {
  width: 80px;
  height: 80px;
  margin-bottom: 10px;
}

.logo h1 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.form-container h2 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 20px;
}

.input-group {
  position: relative;
  margin-bottom: 25px;
}

.input-group input {
  width: 100%;
  padding: 12px 40px 12px 15px;
  border: 1px solid #e1e1e1;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s;
}

.input-group input:focus {
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
  outline: none;
}

.input-icon {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.remember-me {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.remember-me label {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  cursor: pointer;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s;
}

.submit-btn:hover {
  background: #45a049;
}

.submit-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.form-footer {
  margin-top: 20px;
  text-align: center;
}

.toggle-btn {
  background: none;
  border: none;
  color: #4CAF50;
  cursor: pointer;
  font-size: 14px;
  margin-bottom: 20px;
}

.toggle-btn:hover {
  text-decoration: underline;
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.social-btn {
  width: 40px;
  height: 40px;
  border: none;
  border-radius: 50%;
  background: #f5f5f5;
  cursor: pointer;
  transition: transform 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.social-btn:hover {
  transform: scale(1.1);
}

.social-btn img {
  width: 20px;
  height: 20px;
}

.social-text {
  color: #666;
  font-size: 14px;
  margin: 20px 0 10px;
}

.social-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.social-icon {
  font-size: 20px;
}

.error-message {
  color: #ff4444;
  font-size: 12px;
  margin-top: 4px;
  position: absolute;
  bottom: -20px;
  left: 0;
}

@media (max-width: 480px) {
  .auth-card {
    width: 90%;
    padding: 20px;
  }
}
</style>
